﻿using System;
using System.Collections.Generic;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Application = Autodesk.AutoCAD.ApplicationServices.Application;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Galaxy.AutoCAD.Editors;
using Galaxy.AutoCAD.Databases;
using Autodesk.AutoCAD.Geometry;
using Galaxy.AutoCAD.Geometrys;
using Galaxy.AutoCAD.Windows;
using Galaxy.AutoCAD.Options;
using Galaxy.AutoCAD.Strings;
using Galaxy.AutoCAD.Hooks;
using System.Windows.Forms;

[assembly: CommandClass(typeof(Galaxy.AutoCAD.Methods.GeneralMethodTool))]
namespace Galaxy.AutoCAD.Methods
{
    public class GeneralMethodTool
    {
        #region 计算非连续多段线总长
        [CommandMethod("CDP")]
        public static void CalculateDiscretePolyline()
        {
            try
            {
                Document doc = Application.DocumentManager.MdiActiveDocument;
                Editor ed = doc.Editor;
                Database db = doc.Database;
                DBObjectCollection dBObjectCollection = SelectionTool.SelectCollectionDBObject();
                if (dBObjectCollection.Count > 0)
                {
                    List<Polyline> pls = new List<Polyline>();
                    foreach (DBObject dBObject in dBObjectCollection)
                    {
                        if (dBObject is Polyline)
                        {
                            Polyline pl = (Polyline)dBObject;
                            pls.Add(pl);
                        }
                    }
                    double num = 0.0;
                    foreach (Polyline pl in pls)
                    {
                        num += pl.Length;
                    }
                    ed.WriteMessage("多段线的总长为：" + Math.Round(num, 2).ToString() + "mm");
                }
            }
            catch
            {

            }
        }
        #endregion
        #region 创建云线图层
        [CommandMethod("CCLL")]
        public static void CreateCloudLineLayer()
        {
            try
            {
                Document doc = Application.DocumentManager.MdiActiveDocument;
                Database db = doc.Database;
                if (!db.HasLayer("Galaxy-云线"))
                {
                    ObjectId objectId = db.AddLayer("Galaxy-云线", 6);
                }
            }
            catch
            {

            }
        }
        #endregion
        #region 校对
        [CommandMethod("PF")]
        public static void Proofread()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            if (!db.HasLayer("Galaxy-校对"))
            {
                Application.ShowAlertDialog("请载入插件专用前置条件！");
            }
            else
            {
                //设置图层
                db.SetCurrentLayer("Galaxy-校对");
                //文字属性设置
                List<string> textStyleNames = db.GetAllTextStyleName();
                if (textStyleNames.Count > 0)
                {
                    CommonOptionTool.TextPropertyTextStyleNameSet = textStyleNames;
                    using (TextPropertyWindow tpw = new TextPropertyWindow())
                    {
                        Application.ShowModalDialog(tpw);
                    }
                    string textPropertyPass = CommonOptionTool.TextPropertyPass;
                    string textPropertyTextStyleName = CommonOptionTool.TextPropertyTextStyleName;
                    double textPropertyTextHeight = CommonOptionTool.TextPropertyTextHeight;
                    double textPropertyXDeviantValue = CommonOptionTool.TextPropertyXDeviantValue;
                    double textPropertyYDeviantValue = CommonOptionTool.TextPropertyYDeviantValue;
                    ObjectId textStyleId = TextStyleTool.GetTextStyleId(textPropertyTextStyleName);
                    //云线绘制
                    if (textPropertyPass == "1")
                    {
                        Extents3d lineJigExtents3d = LineJigTool.GetLineJigExtens3d();
                        Point3d minPt3d = lineJigExtents3d.MinPoint;
                        Point3d maxPt3d = lineJigExtents3d.MaxPoint;
                        double totalX = lineJigExtents3d.MaxPoint.X - lineJigExtents3d.MinPoint.X;
                        double totalY = lineJigExtents3d.MaxPoint.Y - lineJigExtents3d.MinPoint.Y;
                        if (totalX != 0 && totalY != 0)
                        {
                            double radius = 200;
                            Point2d centerpointx = new Point2d(minPt3d.X + radius, minPt3d.Y);
                            Polyline plx = new Polyline();
                            plx.CreatePolyArc(centerpointx, radius, Math.PI, 2 * Math.PI, 0, 50);
                            ObjectId objIdx = db.AddToModelSpace(plx);
                            ObjectIdCollection objIdColx = objIdx.ArrayRectang(1, (int)(totalX / (2 * radius)), radius, 2 * radius);
                            double radiusLastx = totalX - 2 * radius * (objIdColx.Count);
                            Point2d centerpointLasex = new Point2d(maxPt3d.X - radiusLastx / 2, minPt3d.Y);
                            Polyline plxLastx = new Polyline();
                            plxLastx.CreatePolyArc(centerpointLasex, radiusLastx / 2, Math.PI, 2 * Math.PI, 0, 50);
                            ObjectId objIdLasex = db.AddToModelSpace(plxLastx);
                            ObjectIdCollection allObjectIds = new ObjectIdCollection();
                            ObjectIdCollection allObjectIdxs = new ObjectIdCollection();
                            foreach (ObjectId id in objIdColx)
                            {
                                allObjectIdxs.Add(id);
                                allObjectIds.Add(id);
                            }
                            allObjectIdxs.Add(objIdLasex);
                            allObjectIds.Add(objIdLasex);
                            foreach (ObjectId id in allObjectIdxs)
                            {
                                ObjectId tempObjectId = id.Mirror(Point3dTool.GetCentrePoint(minPt3d, maxPt3d), new Point3d(Point3dTool.GetCentrePoint(minPt3d, maxPt3d).X + 100, Point3dTool.GetCentrePoint(minPt3d, maxPt3d).Y, Point3dTool.GetCentrePoint(minPt3d, maxPt3d).Z), false);
                                allObjectIds.Add(tempObjectId);
                            }
                            Point2d centerpointy = new Point2d(maxPt3d.X, minPt3d.Y + radius);
                            Polyline ply = new Polyline();
                            ply.CreatePolyArc(centerpointy, radius, 3 * Math.PI / 2, 5 * Math.PI / 2, 0, 50);
                            ObjectId objIdy = db.AddToModelSpace(ply);
                            ObjectIdCollection objIdColy = objIdy.ArrayRectang((int)(totalY / (2 * radius)), 1, 2 * radius, radius);
                            double radiusLasty = totalY - 2 * radius * (objIdColy.Count);
                            Point2d centerpointLasey = new Point2d(maxPt3d.X, maxPt3d.Y - radiusLasty / 2);
                            Polyline plyLast = new Polyline();
                            plyLast.CreatePolyArc(centerpointLasey, radiusLasty / 2, 3 * Math.PI / 2, 5 * Math.PI / 2, 0, 50);
                            ObjectId objIdLasey = db.AddToModelSpace(plyLast);
                            ObjectIdCollection allObjectIdys = new ObjectIdCollection();
                            foreach (ObjectId id in objIdColy)
                            {
                                allObjectIdys.Add(id);
                                allObjectIds.Add(id);
                            }
                            allObjectIdys.Add(objIdLasey);
                            allObjectIds.Add(objIdLasey);
                            foreach (ObjectId id in allObjectIdys)
                            {
                                ObjectId tempObjectId = id.Mirror(Point3dTool.GetCentrePoint(minPt3d, maxPt3d), new Point3d(Point3dTool.GetCentrePoint(minPt3d, maxPt3d).X, Point3dTool.GetCentrePoint(minPt3d, maxPt3d).Y + 100, Point3dTool.GetCentrePoint(minPt3d, maxPt3d).Z), false);
                                allObjectIds.Add(tempObjectId);
                            }
                            //List<Entity> ents = new List<Entity>();
                            //foreach (ObjectId id in allObjectIds)
                            //{
                            //    //Entity ent = id.GetObject(OpenMode.ForWrite) as Entity;
                            //    //ents.Add((Entity)id.GetObject(OpenMode.ForRead).Clone());
                            //    //ent.Remove();
                            //}
                            //ObjectId blockRecordId = db.AddBlockTableRecord(StringTool.GetRandomString(8, true, true, true, false, "Galaxy-校对"), ents);
                            //BlockTableRecord btr = blockRecordId.GetObject(OpenMode.ForRead) as BlockTableRecord;
                            //string blockName = btr.Name;
                            //ObjectId blockId = db.InsertBlockReference("0", blockName, Point3dTool.GetCentrePoint(minPt3d, maxPt3d), new Scale3d(0), 0.0);
                        }
                    }
                }
            }
            //        if (totalX != 0 && totalY != 0)
            //        {
            //            double radius = 200;
            //            Point2d centerpointx = new Point2d(minPt3d.X + radius, minPt3d.Y);
            //            Polyline plx = new Polyline();
            //            plx.CreatePolyArc(centerpointx, radius, Math.PI, 2 * Math.PI, 0, 50);
            //            ObjectId objIdx = db.AddToModelSpace(plx);
            //            ObjectIdCollection objIdColx = objIdx.ArrayRectang(1, (int)(totalX / (2 * radius)), radius, 2 * radius);
            //            double radiusLastx = totalX - 2 * radius * (objIdColx.Count);
            //            Point2d centerpointLasex = new Point2d(maxPt3d.X - radiusLastx / 2, minPt3d.Y);
            //            Polyline plxLastx = new Polyline();
            //            plxLastx.CreatePolyArc(centerpointLasex, radiusLastx / 2, Math.PI, 2 * Math.PI, 0, 50);
            //            ObjectId objIdLasex = db.AddToModelSpace(plxLastx);
            //            ObjectIdCollection allObjectIdxs = new ObjectIdCollection();
            //            foreach (ObjectId id in objIdColx)
            //            {
            //                allObjectIdxs.Add(id);
            //            }
            //            allObjectIdxs.Add(objIdLasex);
            //            foreach (ObjectId id in allObjectIdxs)
            //            {
            //                id.Mirror(Point3dTool.GetCentrePoint(minPt3d, maxPt3d), new Point3d(Point3dTool.GetCentrePoint(minPt3d, maxPt3d).X + 100, Point3dTool.GetCentrePoint(minPt3d, maxPt3d).Y, Point3dTool.GetCentrePoint(minPt3d, maxPt3d).Z), false);
            //            }
            //            Point2d centerpointy = new Point2d(maxPt3d.X, minPt3d.Y + radius);
            //            Polyline ply = new Polyline();
            //            ply.CreatePolyArc(centerpointy, radius, 3 * Math.PI / 2, 5 * Math.PI / 2, 0, 50);
            //            ObjectId objIdy = db.AddToModelSpace(ply);
            //            ObjectIdCollection objIdColy = objIdy.ArrayRectang((int)(totalY / (2 * radius)), 1, 2 * radius, radius);
            //            double radiusLasty = totalY - 2 * radius * (objIdColy.Count);
            //            Point2d centerpointLasey = new Point2d(maxPt3d.X, maxPt3d.Y - radiusLasty / 2);
            //            Polyline plyLast = new Polyline();
            //            plyLast.CreatePolyArc(centerpointLasey, radiusLasty / 2, 3 * Math.PI / 2, 5 * Math.PI / 2, 0, 50);
            //            ObjectId objIdLasey = db.AddToModelSpace(plyLast);
            //            ObjectIdCollection allObjectIdys = new ObjectIdCollection();
            //            foreach (ObjectId id in objIdColy)
            //            {
            //                allObjectIdys.Add(id);
            //            }
            //            allObjectIdys.Add(objIdLasey);
            //            foreach (ObjectId id in allObjectIdys)
            //            {
            //                id.Mirror(Point3dTool.GetCentrePoint(minPt3d, maxPt3d), new Point3d(Point3dTool.GetCentrePoint(minPt3d, maxPt3d).X, Point3dTool.GetCentrePoint(minPt3d, maxPt3d).Y + 100, Point3dTool.GetCentrePoint(minPt3d, maxPt3d).Z), false);
            //            }
            //            using (ProofreadWindow pw = new ProofreadWindow())
            //            {
            //                Application.ShowModalDialog(pw);
            //            }
            //            string proofreadPass = GeneralOptionTool.ProofreadPass;
            //            string proofreadStandardClauses = GeneralOptionTool.ProofreadStandardClauses;
            //            string proofreadStandardNumber = GeneralOptionTool.ProofreadStandardNumber;
            //            string proofreadStandardClass = GeneralOptionTool.ProofreadStandardClass;
            //            int proofreadStandardGrade = GeneralOptionTool.ProofreadStandardGrade;
            //            if (proofreadPass == "1")
            //            {
            //                Point3d endPt = ed.InputPoint("请输入点");
            //                ObjectId lineId = db.CreateLine(Point3dTool.GetCentrePoint(minPt3d, maxPt3d), endPt);
            //                string topString = proofreadStandardClass + "：" + proofreadStandardClauses;
            //                string downString = proofreadStandardGrade + "分：" + proofreadStandardNumber;

            //                if (textStyleNames.Count > 0)
            //                {

            //                    if (textPropertyPass == "1")
            //                    {
            //                        if (textStyleId != ObjectId.Null)
            //                        {
            //                            DBText topDBText = TextTool.CreateDBText(topString, Point3d.Origin, textPropertyTextHeight, 0);
            //                            DBText downDBText = TextTool.CreateDBText(downString, Point3d.Origin, textPropertyTextHeight, 0);
            //                            Point3d topMinPoint = topDBText.Bounds.Value.MinPoint;
            //                            Point3d topMaxPoint = topDBText.Bounds.Value.MaxPoint;
            //                            double topLenght = topMaxPoint.X - topMinPoint.X;
            //                            Point3d downMinPoint = downDBText.Bounds.Value.MinPoint;
            //                            Point3d downMaxPoint = downDBText.Bounds.Value.MaxPoint;
            //                            double downLenght = downMaxPoint.X - downMinPoint.X;
            //                            double lenght = Math.Max(topLenght, downLenght);
            //                            Point3d topCentrePoint = topDBText.GetEntityCentre();
            //                            Point3d downCentrePoint = downDBText.GetEntityCentre();
            //                            ObjectId topObjId = db.AddToModelSpace(topDBText);
            //                            ObjectId downObjId = db.AddToModelSpace(downDBText);
            //                            topObjId.SetDBTextProperty(textStyleId);
            //                            downObjId.SetDBTextProperty(textStyleId);


            //                            Point2d pt1 = new Point2d(endPt.X, endPt.Y);
            //                            Point2d pt2 = new Point2d(endPt.X + lenght, endPt.Y - 700);
            //                            Polyline rec = new Polyline();
            //                            rec.CreateRectangle(pt1, pt2);
            //                            db.AddToModelSpace(rec);
            //                        }
            //                    }
            //                }
            //            }
            //        }
            //    }
            //}
        }
        #endregion
        #region 绘制云线
        [CommandMethod("DCL")]
        public static void DrawCloudLine()
        {
            try
            {
                Document doc = Application.DocumentManager.MdiActiveDocument;
                Database db = doc.Database;
                Editor ed = doc.Editor;
                ObjectId objectId = ObjectId.Null;
                LineJig lj = new LineJig();
                PromptResult pr = ed.Drag(lj);
                if (pr.Status == PromptStatus.OK)
                {
                    lj.SetCounter(1);
                    pr = ed.Drag(lj);
                    objectId = db.AddToModelSpace(lj.Entity);
                }
                DBObjectCollection dBObjCol = SelectionTool.SelectLastCreateDBObject();
                if (dBObjCol.Count == 1)
                {
                    if (dBObjCol[0] is Line)
                    {
                        Line line = (Line)dBObjCol[0];
                        Extents3d lineExt = line.Bounds.Value;
                        Point3d minPt3d = lineExt.MinPoint;
                        Point3d maxPt3d = lineExt.MaxPoint;
                        double totalX = lineExt.MaxPoint.X - lineExt.MinPoint.X;
                        double totalY = lineExt.MaxPoint.Y - lineExt.MinPoint.Y;
                        line.ObjectId.Remove();
                        if (totalX != 0 && totalY != 0)
                        {
                            double radius = 200;
                            Point2d centerpointx = new Point2d(minPt3d.X + radius, minPt3d.Y);
                            Polyline plx = new Polyline();
                            plx.CreatePolyArc(centerpointx, radius, Math.PI, 2 * Math.PI, 0, 50);
                            ObjectId objIdx = db.AddToModelSpace(plx);
                            ObjectIdCollection objIdColx = objIdx.ArrayRectang(1, (int)(totalX / (2 * radius)), radius, 2 * radius);
                            double radiusLastx = totalX - 2 * radius * (objIdColx.Count);
                            Point2d centerpointLasex = new Point2d(maxPt3d.X - radiusLastx / 2, minPt3d.Y);
                            Polyline plxLastx = new Polyline();
                            plxLastx.CreatePolyArc(centerpointLasex, radiusLastx / 2, Math.PI, 2 * Math.PI, 0, 50);
                            ObjectId objIdLasex = db.AddToModelSpace(plxLastx);
                            ObjectIdCollection allObjectIdxs = new ObjectIdCollection();
                            foreach (ObjectId id in objIdColx)
                            {
                                allObjectIdxs.Add(id);
                            }
                            allObjectIdxs.Add(objIdLasex);
                            foreach (ObjectId id in allObjectIdxs)
                            {
                                id.Mirror(Point3dTool.GetCentrePoint(minPt3d, maxPt3d), new Point3d(Point3dTool.GetCentrePoint(minPt3d, maxPt3d).X + 100, Point3dTool.GetCentrePoint(minPt3d, maxPt3d).Y, Point3dTool.GetCentrePoint(minPt3d, maxPt3d).Z), false);
                            }
                            Point2d centerpointy = new Point2d(maxPt3d.X, minPt3d.Y + radius);
                            Polyline ply = new Polyline();
                            ply.CreatePolyArc(centerpointy, radius, 3 * Math.PI / 2, 5 * Math.PI / 2, 0, 50);
                            ObjectId objIdy = db.AddToModelSpace(ply);
                            ObjectIdCollection objIdColy = objIdy.ArrayRectang((int)(totalY / (2 * radius)), 1, 2 * radius, radius);
                            double radiusLasty = totalY - 2 * radius * (objIdColy.Count);
                            Point2d centerpointLasey = new Point2d(maxPt3d.X, maxPt3d.Y - radiusLasty / 2);
                            Polyline plyLast = new Polyline();
                            plyLast.CreatePolyArc(centerpointLasey, radiusLasty / 2, 3 * Math.PI / 2, 5 * Math.PI / 2, 0, 50);
                            ObjectId objIdLasey = db.AddToModelSpace(plyLast);
                            ObjectIdCollection allObjectIdys = new ObjectIdCollection();
                            foreach (ObjectId id in objIdColy)
                            {
                                allObjectIdys.Add(id);
                            }
                            allObjectIdys.Add(objIdLasey);
                            foreach (ObjectId id in allObjectIdys)
                            {
                                id.Mirror(Point3dTool.GetCentrePoint(minPt3d, maxPt3d), new Point3d(Point3dTool.GetCentrePoint(minPt3d, maxPt3d).X, Point3dTool.GetCentrePoint(minPt3d, maxPt3d).Y + 100, Point3dTool.GetCentrePoint(minPt3d, maxPt3d).Z), false);
                            }
                        }
                    }
                }
            }
            catch
            {

            }
        }
        #endregion
        #region 创建多段线面积图层
        [CommandMethod("CPAL")]
        public static void CreatePolylineAreaLayer()
        {
            try
            {
                Document doc = Application.DocumentManager.MdiActiveDocument;
                Database db = doc.Database;
                if (!db.HasLayer("Galaxy-多段线-面积"))
                {
                    ObjectId objectId = db.AddLayer("Galaxy-多段线-面积", 7);
                }
            }
            catch
            {

            }
        }
        #endregion
        #region 计算多段线面积
        [CommandMethod("CPA")]
        public static void CalculatePolylineArea()
        {
            try
            {
                Document doc = Application.DocumentManager.MdiActiveDocument;
                Editor ed = doc.Editor;
                Database db = doc.Database;
                if (!db.HasLayer("Galaxy-多段线-面积"))
                {
                    Application.ShowAlertDialog("请先点击一般模块前置条件!");
                }
                else
                {
                    db.SetCurrentLayer("Galaxy-多段线-面积");
                    List<string> textStyleNames = db.GetAllTextStyleName();
                    if (textStyleNames.Count > 0)
                    {
                        CommonOptionTool.TextPropertyTextStyleNameSet = textStyleNames;
                        using (TextPropertyWindow textPropertyWindow = new TextPropertyWindow())
                        {
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowModalDialog(textPropertyWindow);
                        }
                        if (CommonOptionTool.TextPropertyPass == "1")
                        {
                            string textPropertyTextStyleName = CommonOptionTool.TextPropertyTextStyleName;
                            double textPropertyTextHeight = CommonOptionTool.TextPropertyTextHeight;
                            double textPropertyXDeviantValue = CommonOptionTool.TextPropertyXDeviantValue;
                            double textPropertyYDeviantValue = CommonOptionTool.TextPropertyYDeviantValue;
                            if (textPropertyTextStyleName != null)
                            {
                                ObjectId textStyleId = TextStyleTool.GetTextStyleId(textPropertyTextStyleName);
                                if (textStyleId != ObjectId.Null)
                                {

                                    DBObjectCollection dBObjectCollection = SelectionTool.SelectCollectionDBObject();
                                    if (dBObjectCollection.Count > 0)
                                    {
                                        foreach (DBObject dBObject in dBObjectCollection)
                                        {
                                            if (dBObject is Polyline)
                                            {
                                                Polyline polyline = (Polyline)dBObject;
                                                if (polyline.Area > 0.0)
                                                {
                                                    double area = polyline.Area;
                                                    string textString = Math.Round(area / 1000000.0, 2).ToString("0.00") + "m²";
                                                    Point3d plCenterPoint = polyline.GetEntityCentre();
                                                    DBText dBText = TextTool.CreateDBText(textString, Point3d.Origin, textPropertyTextHeight, 0.0);
                                                    ObjectId dbTextId = db.AddToModelSpace(dBText);
                                                    TextTool.SetDBTextProperty(dbTextId, textStyleId);
                                                    Point3d textCenterPoint = dBText.GetEntityCentre();
                                                    dbTextId.Move(textCenterPoint, plCenterPoint);
                                                    if (textPropertyXDeviantValue != 0.0 || textPropertyYDeviantValue != 0.0)
                                                    {
                                                        Point3d targetPoint = new Point3d(plCenterPoint.X + textPropertyXDeviantValue, plCenterPoint.Y + textPropertyYDeviantValue, plCenterPoint.Z);
                                                        dbTextId.Move(plCenterPoint, targetPoint);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        Autodesk.AutoCAD.ApplicationServices.Core.Application.ShowAlertDialog("请载入文字样式");
                    }
                    db.SetCurrentLayer("0");
                }
            }
            catch
            {
            }
        }
        #endregion
        #region 绘制偏移矩形
        //定义参数值a
        private int a = 0;
        //判断按下的键（Escape） 
        private void hook_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyValue == (int)System.Windows.Forms.Keys.Escape)
            {
                a = 1;
            }
        }
        [CommandMethod("DOR")]
        public void DrawOffsetRectangle()
        {
            try
            {
                KeyboardHook k_hook = new KeyboardHook();
                k_hook.KeyDownEvent += new System.Windows.Forms.KeyEventHandler(hook_KeyDown);//钩住键按下 
                k_hook.Start();//安装键盘钩子
                Document doc = Application.DocumentManager.MdiActiveDocument;
                Editor ed = doc.Editor;
                Database db = doc.Database;
                double myDouble = ed.InputDouble("请输入偏移值！(注：负数往内偏移，正数往外偏移)");
                a = 0;
                do
                {
                    Point3d firstPoint3d = ed.InputPoint("请输入第一点！（或者按两下ESC键退出）");
                    if (firstPoint3d != null)
                    {
                        Point3d secondPoint3d = ed.InputPoint("请输入第二点！（或者两下按ESC键退出）");
                        if (secondPoint3d != null)
                        {
                            Point3d minPoint3d = new Point3d(Math.Min(firstPoint3d.X, secondPoint3d.X), Math.Min(firstPoint3d.Y, secondPoint3d.Y), firstPoint3d.Z);
                            Point3d maxPoint3d = new Point3d(Math.Max(firstPoint3d.X, secondPoint3d.X), Math.Max(firstPoint3d.Y, secondPoint3d.Y), firstPoint3d.Z);
                            Point2d pt1 = new Point2d(minPoint3d.X - myDouble, minPoint3d.Y - myDouble);
                            Point2d pt2 = new Point2d(maxPoint3d.X + myDouble, maxPoint3d.Y + myDouble);
                            Polyline pl = new Polyline();
                            pl.CreateRectangle(pt1, pt2);
                            ObjectId objectId2 = db.AddToModelSpace(pl);
                        }
                    }
                }
                while (a == 0);
                k_hook.Stop();//卸载键盘钩子
            }
            catch
            {

            }
        }
        #endregion
        #region 绘制偏移多段线
        [CommandMethod("DOP")]
        public void DrawOffsetPolyline()
        {
            try
            {
                KeyboardHook k_hook = new KeyboardHook();
                k_hook.KeyDownEvent += new System.Windows.Forms.KeyEventHandler(hook_KeyDown);//钩住键按下 
                k_hook.Start();//安装键盘钩子
                Document doc = Application.DocumentManager.MdiActiveDocument;
                Editor ed = doc.Editor;
                Database db = doc.Database;
                double myDouble = ed.InputDouble("请输入偏移值！(注：负数往内偏移，正数往外偏移)");
                Point3dCollection pt3ds = new Point3dCollection();
                a = 0;
                do
                {
                    Point3d pt3d = ed.InputPoint("请输入点！（或者按ESC键退出）");
                    pt3ds.Add(pt3d);
                }
                while (a == 0);
            }
            catch
            {

            }
        }
        #endregion
        #region 批量偏移多段线
        [CommandMethod("BOP")]
        public void BatchOffsetPolyline()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            double myDouble = ed.InputDouble("请输入偏移值！(注：负数往内偏移，正数往外偏移)");
            string[] keywords = new string[] { "Y", "N" };
            string keyword = ed.InputKeyword("是否删除原多段线？", keywords);
            DBObjectCollection dBObjectCollection = SelectionTool.SelectCollectionDBObject();
            if (dBObjectCollection.Count > 0)
            {
                List<Polyline> pls = new List<Polyline>();
                foreach (DBObject dBObject in dBObjectCollection)
                {
                    if (dBObject is Polyline)
                    {
                        Polyline pl = (Polyline)dBObject;
                        pls.Add(pl);
                    }
                }
                if (pls.Count > 0)
                {
                    foreach (Polyline outPl in pls)
                    {
                        if (outPl.NumberOfVertices >= 3)
                        {
                            if (outPl.IsClockwiseOrAnticlockwise() == PolylineDirection.Clockwise)
                            {
                                List<Curve> curves = outPl.Offset(myDouble);
                                foreach (Curve curve in curves)
                                {
                                    db.AddToModelSpace(curve);
                                }
                                if (keyword == "Y")
                                {
                                    outPl.ObjectId.Remove();
                                }
                            }
                            else if (outPl.IsClockwiseOrAnticlockwise() == PolylineDirection.Anticlockwise)
                            {
                                List<Curve> curves = outPl.Offset(-myDouble);
                                foreach (Curve curve in curves)
                                {
                                    db.AddToModelSpace(curve);
                                }
                                if (keyword == "Y")
                                {
                                    outPl.ObjectId.Remove();
                                }
                            }
                        }
                    }
                }
            }
        }
        #endregion
        #region 修改快捷键
        [CommandMethod("MSK")]
        public void ModifyShortcutKeys()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
        }
        #endregion
        #region 批量将模型空间中的多行文字转换成多行文字
        [CommandMethod("ExplodeMText")]
        public static void ExplodeMText()
        {
            string[] dwgPaths = null;
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Title = "请选择dwg图纸";
                ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                ofd.Multiselect = true;
                ofd.Filter = "(*.dwg)|*.dwg";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    dwgPaths = ofd.FileNames;
                }
            }
            if (dwgPaths != null)
            {
                Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                foreach (string dwgPath in dwgPaths)
                {
                    using (Database db = new Database(false, true))
                    {
                        try
                        {
                            db.ReadDwgFile(dwgPath, FileOpenMode.OpenForReadAndAllShare, true, "");
                            db.CloseInput(true);
                            using (Transaction trans = db.TransactionManager.StartTransaction())
                            {
                                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite);
                                BlockTableRecord modelSpace = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                                foreach (ObjectId outObjectId in modelSpace)
                                {
                                    DBObject dBObject = (Entity)outObjectId.GetObject(OpenMode.ForWrite);
                                    if (dBObject is MText)
                                    {
                                        MText mText = (MText)dBObject;
                                        using (DBObjectCollection dBOjects = new DBObjectCollection())
                                        {
                                            mText.Explode(dBOjects);
                                            mText.Erase(true);
                                            if (dBOjects.Count > 0)
                                            {
                                                foreach (DBObject outDBOject in dBOjects)
                                                {
                                                    if (outDBOject is DBText)
                                                    {
                                                        DBText dBText = (DBText)outDBOject;
                                                        {
                                                            modelSpace.AppendEntity(dBText);
                                                            trans.AddNewlyCreatedDBObject(dBText, true);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                trans.Commit();
                            }
                            db.SaveAs(dwgPath, DwgVersion.Current);
                        }
                        catch (System.Exception ex)
                        {
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message + "\n" + ex.StackTrace.ToString());
                            return;
                        }
                    }
                }
            }
        }
        #endregion
        #region 批量将模型空间中的块中块变成一层块
        [CommandMethod("ExplodeBlockInBlock")]
        public static void ExplodeBlockInBlock()
        {
            string[] dwgPaths = null;
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Title = "请选择dwg图纸";
                ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                ofd.Multiselect = true;
                ofd.Filter = "(*.dwg)|*.dwg";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    dwgPaths = ofd.FileNames;
                }
            }
            if (dwgPaths != null)
            {
                Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                foreach (string dwgPath in dwgPaths)
                {
                    using (Database db = new Database(false, true))
                    {
                        try
                        {
                            db.ReadDwgFile(dwgPath, FileOpenMode.OpenForReadAndAllShare, true, "");
                            db.CloseInput(true);
                            using (Transaction trans = db.TransactionManager.StartTransaction())
                            {
                                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                                BlockTableRecord modelSpace = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
                                if (modelSpace.IsContainBlockReference())
                                {
                                    //遍历模型空间中的块
                                    foreach (ObjectId outIdOne in modelSpace)
                                    {
                                        DBObject dBObjOne = outIdOne.GetObject(OpenMode.ForRead);
                                        if (dBObjOne is BlockReference)
                                        {
                                            BlockReference brOne = (BlockReference)dBObjOne;
                                            BlockTableRecord btrOne = (BlockTableRecord)brOne.BlockTableRecord.GetObject(OpenMode.ForRead);
                                            while (btrOne.IsContainBlockReference())
                                            {
                                                //遍历模型空间中的块中块
                                                foreach (ObjectId outIdTwo in btrOne)
                                                {
                                                    using (DBObjectCollection dBObjCol = new DBObjectCollection())
                                                    {
                                                        DBObject dBObjTwo = outIdTwo.GetObject(OpenMode.ForRead);
                                                        if (dBObjTwo is BlockReference)
                                                        {
                                                            BlockReference brTwo = (BlockReference)dBObjTwo;
                                                            brTwo.UpgradeOpen();
                                                            btrOne.UpgradeOpen();
                                                            brTwo.Explode(dBObjCol);
                                                            brTwo.Erase(true);
                                                            foreach (DBObject outDBObj in dBObjCol)
                                                            {
                                                                if (outDBObj is Entity)
                                                                {
                                                                    Entity ent = (Entity)outDBObj;
                                                                    btrOne.AppendEntity(ent);
                                                                    trans.AddNewlyCreatedDBObject(ent, true);
                                                                }
                                                            }
                                                            btrOne.DowngradeOpen();
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                trans.Commit();
                            }
                            db.SaveAs(dwgPath, DwgVersion.Current);
                        }
                        catch (System.Exception ex)
                        {
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message + "\n" + ex.StackTrace.ToString());
                            return;
                        }
                    }
                }
            }
        }
    }
}
#endregion